//
//  GQDistributePhotoController.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/15.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQDistributePhotoController.h"
#import "GQDistributeStatusController.h"
#import "GQMainNavigationController.h"
#import "GQDistributPhotoInfo.h"
#import "GQTabBar.h"
#import "MBProgressHUD.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface GQDistributePhotoController ()

@property (strong, nonatomic) NSMutableArray *imageArrM;
@property (strong, nonatomic) NSMutableArray *selectedBtns;
@property (strong, nonatomic) NSMutableArray *btns;
@property (strong, nonatomic) UILabel *stepCount;
@property (strong, nonatomic) NSMutableArray *selectedImages;
@property (strong, nonatomic) NSMutableArray *groups;
@property (strong, nonatomic) NSMutableArray *albumNames;
@property (strong, nonatomic) NSMutableArray *dataImagesM;
@property (weak, nonatomic) UIButton *selectedBtn;
@property (weak, nonatomic) UIView *coverView;
@property (weak, nonatomic) UIView *topCoverView;
@property (weak, nonatomic) UIView *dropRefreshView;
@property (weak, nonatomic) UIImageView *arrowImage;
@property (strong, nonatomic) UIView *containView;
@property (strong, nonatomic) NSMutableDictionary *imageDict;
@property (weak, nonatomic) UILabel *titleLabel;
@property (weak, nonatomic) UIView *titleView;

@end

@implementation GQDistributePhotoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"home_close"] style:UIBarButtonItemStylePlain target:self action:@selector(cancelToBack)];
    
    UIButton *titleView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 82, 22)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 65, 22)];
    titleLabel.text = @"相册胶卷";
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textAlignment = NSTextAlignmentRight;
    titleLabel.textColor = [UIColor whiteColor];
    
    [titleView addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"distribute_dropRefresh"]];
    self.arrowImage = imageView;
    imageView.frame = CGRectMake(65, 0, 22, 22);
    [titleView addSubview:imageView];
    self.navigationItem.titleView = titleView;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleViewTapDidClick)];
    [titleView addGestureRecognizer:tapGestureRecognizer];
    
    [self getImages];
    [self setUpBottomToolView];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSTimer *myTimer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(updateImages:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
    
}

- (void)updateImages:(NSTimer *)timer
{
    if (self.dataImagesM != nil) {
        [timer invalidate];
        timer = nil;
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        [self setUpChildImageView:self.dataImagesM];
    }
}

#pragma mark - 创建图片
- (void)setUpChildImageView:(NSArray *)imageArr
{
    [self.containView removeFromSuperview];
    self.stepCount.text = @"0/5";
    [self.selectedBtns removeAllObjects];
    [self.selectedImages removeAllObjects];
    [self.btns removeAllObjects];
    self.containView = nil;
    
    NSInteger count = imageArr.count;
    CGFloat margin = 10;
    CGFloat width = (self.view.width - 4 * margin) / 3;

    self.containView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - kToolBarHeight)];
    [self.view addSubview:self.containView];
    self.containView.alpha = 0;
    
    for (int i = 0; i < count; i++) {
        UIButton *imageBtn = [[UIButton alloc] init];
        imageBtn.x = margin + (width + margin) * (i % 3);
        imageBtn.y = kNavigatationBarHeight + margin + (margin + width) * (i / 3);
        imageBtn.width = width;
        imageBtn.height = width;
        imageBtn.tag = i;
        [self.imageArrM addObject:imageArr[i]];
        [imageBtn setImage:imageArr[i] forState:UIControlStateNormal];
        [imageBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat width = 22;
        UIButton *selectedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        selectedBtn.frame = CGRectMake(imageBtn.width - width - 2, 2, width, width);
        [selectedBtn setImage:[UIImage imageNamed:@"distribute_select"] forState:UIControlStateNormal];
        [selectedBtn setImage:[UIImage imageNamed:@"distribute_selected"] forState:UIControlStateSelected];
        selectedBtn.tag = i;
        [selectedBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [imageBtn addSubview:selectedBtn];
        [self.btns addObject:selectedBtn];
        
        [self.containView addSubview:imageBtn];
    }
    [UIView animateWithDuration:1.0 animations:^{
        self.containView.alpha = 1.0;
    }];
}

- (void)titleViewTapDidClick
{
    CGFloat dropRefreshCellHeight = 44;
    UIView *dropRefreshView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavigatationBarHeight - 220, self.view.width, 220)];
    dropRefreshView.backgroundColor = [UIColor whiteColor];
    self.dropRefreshView = dropRefreshView;
    NSInteger count = self.groups.count;
    for (int i = 0; i < count; i++) {
        UIButton *imageBtn = [[UIButton alloc] init];
        imageBtn.x = 0;
        imageBtn.y = i * dropRefreshCellHeight;
        imageBtn.width = dropRefreshView.width;
        imageBtn.height = dropRefreshCellHeight;
        imageBtn.tag = i;
        [imageBtn addTarget:self action:@selector(imageBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        
        // 相册的封面
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon"]];
        imageView.x = 10;
        imageView.height = 40;
        imageView.width = 40;
        imageView.y = (imageBtn.height - imageView.height) / 2;
        [imageBtn addSubview:imageView];
        
        //相册的名称
        CGSize size = [self.albumNames[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, 16) options:0 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size;
        
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.x = CGRectGetMaxX(imageView.frame) + 10;
        nameLabel.y = (imageBtn.height - size.height) / 2;
        nameLabel.width = size.width;
        nameLabel.height = size.height;
        nameLabel.text = self.albumNames[i];
        nameLabel.font = [UIFont systemFontOfSize:16];
        [imageBtn addSubview:nameLabel];
        
        UILabel *photoNum = [[UILabel alloc] init];
        photoNum.height = 8;
        photoNum.width = 50;
        photoNum.x = CGRectGetMaxX(nameLabel.frame) + 5;
        photoNum.y = CGRectGetMaxY(nameLabel.frame) - photoNum.height - 3;
        photoNum.text = @"720";
        photoNum.font = [UIFont systemFontOfSize:8];
        [imageBtn addSubview:photoNum];
        [dropRefreshView addSubview:imageBtn];
    }
    
    UIView *coverView = [[UIView alloc] initWithFrame:self.view.bounds];
    coverView.backgroundColor = [UIColor clearColor];
    self.coverView = coverView;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(deallocCoverView)];
    [coverView addGestureRecognizer:tap1];
    
    UIView *topCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, self.view.width, kNavigatationBarHeight - 20)];
    topCoverView.backgroundColor = [UIColor clearColor];
    self.topCoverView = topCoverView;
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(deallocCoverView)];
    [topCoverView addGestureRecognizer:tap2];
    [self.navigationController.navigationBar addSubview:topCoverView];
    [self.view addSubview:coverView];
    [self.view addSubview:dropRefreshView];
    
    self.arrowImage.transform = CGAffineTransformRotate(self.arrowImage.transform, M_PI);
    
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.7 options:0 animations:^{
        dropRefreshView.y += 220;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)imageBtnDidClick:(UIButton *)btn
{
    self.selectedBtn.backgroundColor = [UIColor whiteColor];
    btn.backgroundColor = [UIColor lightGrayColor];
    self.selectedBtn = btn;
    NSString *str = [NSString stringWithFormat:@"%ld", btn.tag];
    NSArray *arr = self.imageDict[str];
    [self deallocCoverView];
    [self setUpChildImageView:arr];
    self.titleLabel.text = self.albumNames[btn.tag];
    
    self.arrowImage.transform = CGAffineTransformRotate(self.arrowImage.transform, M_PI);
    [UIView animateWithDuration:1.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.7 options:0 animations:^{
        self.dropRefreshView.y -= 220;
    } completion:^(BOOL finished) {
        [self.dropRefreshView removeFromSuperview];
        [self.coverView removeFromSuperview];
        [self.topCoverView removeFromSuperview];
        self.coverView = nil;
        self.dropRefreshView = nil;
        self.topCoverView = nil;
        
    }];
    
}

- (void)deallocCoverView
{
    self.arrowImage.transform = CGAffineTransformRotate(self.arrowImage.transform, M_PI);
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.7 options:0 animations:^{
        self.dropRefreshView.y -= 220;
    } completion:^(BOOL finished) {
        [self.dropRefreshView removeFromSuperview];
        [self.coverView removeFromSuperview];
        [self.topCoverView removeFromSuperview];
        self.coverView = nil;
        self.dropRefreshView = nil;
        self.topCoverView = nil;
    }];
}

- (void)getImages
{
        ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *myError){
            NSLog(@"相册访问失败 = %@", [myError localizedDescription]);
            if ([myError.localizedDescription rangeOfString:@"Global denied access"].location != NSNotFound) {
                NSLog(@"无法访问相册。请在'设置->定位服务'设置为打开状态。");
            }else{
                NSLog(@"相册访问失败！");
            }
        };
    
    __block int i = 0;
        ALAssetsLibraryGroupsEnumerationResultsBlock libraryGroupsEnumeration = ^(ALAssetsGroup *group, BOOL *stop){
            if(group != nil){
                NSString *albumName = [group valueForProperty:@"ALAssetsGroupPropertyName"];
                [self.albumNames addObject:albumName];
                [self.groups addObject:group];
            }else{
                [self.groups enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    
                    NSMutableArray *arr = [NSMutableArray array];
                    
                    [obj enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                        if ([result thumbnail] != nil) {
                            //照片
                            if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
                                //GQDistributPhotoInfo *GQDP = [[GQDistributPhotoInfo alloc] init];
//                                GQDP.createDate = [result valueForProperty:ALAssetPropertyDate];
//                                GQDP.image  = [UIImage imageWithCGImage:[result thumbnail]];
//                                GQDP.fileName = [[result defaultRepresentation] filename];
//                                GQDP.originalUrl = [[result defaultRepresentation] url];
//                                GQDP.fileSize = [[result defaultRepresentation] size];
                                UIImage *image = [UIImage imageWithCGImage:[result thumbnail]];
                                [self.dataImagesM addObject:image];
                                [arr addObject:image];
                            }
                        }
                    }];
                    
                    [self.imageDict setObject:arr forKey:[NSString stringWithFormat:@"%d", i]];
                    i++;
                }];
            }
        };
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:libraryGroupsEnumeration failureBlock:failureBlock];
}

- (void)btnDidClick:(UIButton *)btn
{
    
    if (self.selectedBtns.count >= 5 && ![self.selectedBtns containsObject:self.btns[btn.tag]]) {
        return;
    }

    UIButton *selectedBtn = self.btns[btn.tag];
    selectedBtn.selected = !selectedBtn.selected;

    if (selectedBtn.selected) {
        [self.selectedBtns addObject:selectedBtn];
        [self.selectedImages addObject:self.imageArrM[btn.tag]];
    }else{
        [self.selectedBtns removeObject:selectedBtn];
        [self.selectedImages removeObject:self.imageArrM[btn.tag]];
    }
    
    self.stepCount.text = [NSString stringWithFormat:@"%ld/5", self.selectedBtns.count];
    
}

- (void)cancelToBack
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)setUpBottomToolView
{
    UIView *containView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 44, self.view.width, 44)];
    [self.view addSubview:containView];
    containView.backgroundColor = [UIColor lightGrayColor];
    
    UIButton *cameraBtn = [[UIButton alloc] init];
    cameraBtn.x = 5;
    cameraBtn.y = (containView.height - 20) / 2;
    cameraBtn.width = 70;
    cameraBtn.height = 20;
    cameraBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cameraBtn setTitle:@"照相机" forState:UIControlStateNormal];
    [cameraBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [containView addSubview:cameraBtn];
    
    UIButton *finishBtn = [[UIButton alloc] init];
    finishBtn.x = containView.width - 40;
    finishBtn.y = (containView.height - 20) / 2;
    finishBtn.width = 35;
    finishBtn.height = 20;
    finishBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [finishBtn addTarget:self action:@selector(finishDidClick) forControlEvents:UIControlEventTouchUpInside];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [containView addSubview:finishBtn];
    
    UILabel *stepCount = [[UILabel alloc] init];
    stepCount.x = CGRectGetMinX(finishBtn.frame) - 30 - 3;
    stepCount.y = (containView.height - 30) / 2;
    stepCount.textAlignment = NSTextAlignmentCenter;
    stepCount.width = 30;
    stepCount.height = 30;
    stepCount.text = @"0/5";
    stepCount.font = [UIFont systemFontOfSize:14];
    stepCount.textColor = [UIColor whiteColor];
    stepCount.backgroundColor = [UIColor colorWithRed:93/255.0 green:215/255.0 blue:248/255.0 alpha:1.0];
    stepCount.layer.masksToBounds = YES;
    stepCount.layer.cornerRadius = 15;
    self.stepCount = stepCount;
    [containView addSubview:stepCount];
}

- (void)finishDidClick
{
    GQDistributeStatusController *GQDSC = [[GQDistributeStatusController alloc] init];
    GQDSC.type = @"photo";
    GQDSC.images = self.selectedImages;
    [self.navigationController pushViewController:GQDSC animated:YES];
}

- (NSMutableArray *)selectedImages
{
    if (_selectedImages == nil) {
        _selectedImages = [NSMutableArray array];
    }
    return _selectedImages;
}

- (NSMutableArray *)dataImagesM
{
    if (_dataImagesM == nil) {
        _dataImagesM = [NSMutableArray array];
    }
    return _dataImagesM;
}

- (NSMutableArray *)groups
{
    if (_groups == nil) {
        _groups = [NSMutableArray array];
    }
    return _groups;
}

- (NSMutableArray *)selectedBtns
{
    if (_selectedBtns == nil) {
        _selectedBtns = [NSMutableArray array];
    }
    return _selectedBtns;
}

- (NSMutableArray *)btns
{
    if (_btns == nil) {
        _btns = [NSMutableArray array];
    }
    return _btns;
}

- (NSMutableArray *)imageArrM
{
    if (_imageArrM == nil) {
        _imageArrM = [NSMutableArray array];
    }
    return _imageArrM;
}

- (NSMutableArray *)albumNames
{
    if (_albumNames == nil) {
        _albumNames = [NSMutableArray array];
    }
    return _albumNames;
}

- (NSMutableDictionary *)imageDict
{
    if (_imageDict == nil) {
        _imageDict = [NSMutableDictionary dictionary];
    }
    return _imageDict;
}

@end
